package cn.suzhang.jsharp.module.sys.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.suzhang.jsharp.common.entity.JsonEntity;
import cn.suzhang.jsharp.module.sys.entity.SysResource;
import cn.suzhang.jsharp.module.sys.service.ResourceService;
import cn.suzhang.jsharp.module.sys.vo.ZtreeView;

/**
 * 
 * @author suzhang
 * @since 2018-02-13
 */
@Controller
@RequestMapping("/admin/resource")
public class ResourceController {

	@Autowired
	private ResourceService service;

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(Model model) {
		List<SysResource> list = service.findAll();
		model.addAttribute("list", list);

		return "admin/resource/resource";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Model model) {
		List<SysResource> list = service.findAll();
		model.addAttribute("list", list);
		return "/admin/resource/form";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> findSearch(SysResource sysResource) {
		Map<String, Object> map = new HashMap<>();
		List<SysResource> list = service.findAll();
		map.put("recordsTotal", list.size());
		map.put("data", list);
		return map;
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable Long id, Model model) {
		SysResource resource = service.find(id);
		model.addAttribute("resource", resource);

		List<SysResource> list = service.findAll();
		model.addAttribute("list", list);

		return "admin/resource/form";
	}

	@RequestMapping(value = { "/edit" }, method = RequestMethod.POST)
	@ResponseBody
	public JsonEntity edit(SysResource resource, Model model) {
		try {
			service.saveOrUpdate(resource);
		} catch (Exception e) {
			return JsonEntity.failure(e.getMessage());
		}
		return JsonEntity.success();
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@ResponseBody
	public JsonEntity delete(@PathVariable Long id, Model model) {
		try {
			service.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonEntity.failure(e.getMessage());
		}
		return JsonEntity.success();
	}

	@RequestMapping("/tree/{resourceId}")
	@ResponseBody
	public List<ZtreeView> tree(@PathVariable Long resourceId) {
		List<ZtreeView> list = service.tree(resourceId);
		return list;
	}

}
